#include "task_doorCntl.h"

#include "tasksInit.h"
#include "task_autoMode.h"

#include <stdint.h>
#include <stdio.h>

#include "los_task.h"
#include "los_queue.h"
#include "los_event.h"

#include "bsp_led.h"
#include "bsp_sg90.h"
#include "bsp_sl2823.h"

static void task_nfcDetect(void);

unsigned int task_doorCntl_id;
TSK_INIT_PARAM_S task_doorCntl_handler = {
    (TSK_ENTRY_FUNC)task_doorCntl,
    26,
    0,
    1280,
    "task_doorCntl",
    0
};

unsigned int task_nfcDetect_id;
TSK_INIT_PARAM_S task_nfcDetect_handler = {
    (TSK_ENTRY_FUNC)task_nfcDetect,
    26,
    0,
    4096,
    "task_nfcDetect",
    0
};

void task_doorCntl(void)
{
    uint8_t cntl_data = 0;
    uint32_t len = sizeof(cntl_data);
    int ret = 0;

    //等待硬件初始化
    LOS_EventRead(&bspInit_ECB, BSPINIT_EVENT_INITOK, LOS_WAITMODE_AND, LOS_WAIT_FOREVER);

    //创建子任务
    ret = LOS_TaskCreate(&task_nfcDetect_id, &task_nfcDetect_handler);
    if(LOS_OK != ret)
    {
        //error
        printf("[task_doorCntl] LOS_TaskCreate task_nfcDetect err, code: 0x%x\n", ret);
    }

    while(1)
    {
        //1. 等待队列
        ret = LOS_QueueReadCopy(doorCntl_qId, (void *)&cntl_data, &len, LOS_WAIT_FOREVER);
        if(LOS_OK != ret)
        {
            printf("[task_doorCntl] LOS_QueueReadCopy error, red: 0x%x\n", ret);
            LOS_Msleep(500);
            continue;
        }
        //if err

        printf("[task_doorCntl] get message from queue, cntl_data:%d\n", cntl_data);

        //2. 执行操作
        event_mode_switch_t autoMode_event;
        if(cntl_data)
        {
            led_toggle(LED1);
            //写模式转换队列
            autoMode_event = EVENT_MODE_SWITCH_TO_HOME;
            LOS_QueueWriteCopy(autoMode_qId, &autoMode_event, sizeof(autoMode_event), 1);

            sg90_door_open();
        }
        else
        {
            //写模式转换队列
            autoMode_event = EVENT_MODE_SWITCH_TO_AWAY;
            LOS_QueueWriteCopy(autoMode_qId, &autoMode_event, sizeof(autoMode_event), 1);

            sg90_door_close();
        }

        LOS_Msleep(100);
    }
}

void task_nfcDetect(void)
{
    int is_valid_card = 0;

    uint8_t door_cntl = 1;

    // uint8_t duty = 3;

    while(1)
    {
#ifdef LPCD_MODE
        is_valid_card = sl2823_lpcd_loop();
#else
        is_valid_card = ls2823_loop();
#endif

        switch(is_valid_card)
        {
        case 0:
            // printf("[tasK_doorCntl] nfc no card find.\n");
            break;
        case 1:
            printf("[task_doorCntl] nfc find unkown card.\n");
            break;
        case 2:
            printf("[task_doorCntl] nfc find currect card, try to open the door.\n");
            door_cntl = !door_cntl;
            LOS_QueueWriteCopy(doorCntl_qId, (void *)&door_cntl, sizeof(door_cntl), 1);
            //if err

            break;
        default :
            break;
        }

        // sg90_setPWM_duty(duty);
        // duty += 1;
        // if(duty > 13) duty = 3;
        LOS_Msleep(100);
    }
}

